package com.example.remotebomb23;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.os.Bundle;
import android.telephony.SmsMessage;

public class SmsReceiver extends BroadcastReceiver  {
	
	public static final String LOG_TAG = "SmsReceiver";
	public static final String SMS_RECEIVED_ACTION = "android.provider.Telephony.SMS_RECEIVED";

	@Override
	public void onReceive(Context context, Intent intent) {
		String action = intent.getAction();
		Log.d(LOG_TAG, "[onReceive][The recive intent is :"+action+"]");
		if (SMS_RECEIVED_ACTION.equals(action)) {
			//Get SMS 
			Bundle bundle = intent.getExtras();
			if (bundle == null) {
				Log.d(LOG_TAG, "[onReceive][Get bundle from intent is null]");
				return ;
			}
			Object[] pdus = (Object[])bundle.get("pdus");
			for (Object pdu : pdus){
				SmsMessage message = SmsMessage.createFromPdu((byte[]) pdu);
				String sender = message.getOriginatingAddress();
				Log.d(LOG_TAG, "[onReceive][SMS sender is:"+sender+"]");
				String msgbody = message.getMessageBody();
				//Log.d(LOG_TAG, "[onReceive][Message body is:"+msgbody+"]");
				//compare the message body with command key word
				if (msgbody != null) {
					Log.d(LOG_TAG, "[onReceive][Got the remote bomb message: "+msgbody+"]");
					if (msgbody.startsWith(SmsCommand.COMMAND_KEY_WORD)) {
						Intent startservice = new Intent(BombService.ACTION_START_DESTORY);
						//startservice.setClassName("com.example.remotebomb23", "BombService");
						startservice.setClass(context, BombService.class);
						startservice.putExtra(BombService.KEY_CMD_MSG, msgbody.trim());
						context.startService(startservice);
						//Abort sms receive intent but if the cmd is find lost phone cmd ,no need abort it
						String[] splitcmd = msgbody.split(SmsCommand.COMAND_SPLIT_KEY);
				    	int cmd = 0;
				    	if (splitcmd.length > 1) {
				    		cmd = Integer.valueOf(splitcmd[1]);
				    	}
				    	if (cmd > 0 && cmd == SmsCommand.FIND_LOST_PHONE) {
				    		Log.d(LOG_TAG, "[onReceive][received command is FIND_LOST_PHONE]");		    		
				    	} else 
				    		abortBroadcast();
					}
				}
			}
		} else {
			Log.d(LOG_TAG, "[onReceive][Receive wrong intent]");
		}	
	}
}
